<script setup lang="ts">
import userApi from '@/view/rbac/user/api/UserApi';
import loginApi from "@/api/sys/LoginApi.ts";
import {useUserStore} from "@/pinia/useUser.ts";
import {onActivated, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import type ISysDepartResp from "@/view/depart/type/resp/ISysDepartResp.ts";
import type SelectItem from "@/components/select/type/SelectItem.ts";
import useSchema from "./composables/useSchema.ts"
import type IFormExpos from "@/components/input/type/expose.ts";
import {removeCookie} from "@/util/cookies.ts";
import {Message} from "@/hook/message/message.ts";

let route = useRoute()
let router = useRouter()
const userStore = useUserStore()
const {passwordChangeModel, passwordSchema, tableColumns} = useSchema()

const passwordFormRef = ref<IFormExpos | null>(null)
const departDialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const exitDialogVisible = ref(false)
const loading = ref(false)
const userCurrentDepart = ref<ISysDepartResp>({})
const userAllDepart = ref<ISysDepartResp[]>()
const selectItems = ref<SelectItem[]>()
//切换部门时，选中的部门code
const checkedDepartCode = ref<string>()

/**
 * 拉取用户的部门信息
 */
const fetchUserDepart = () => {
  userApi.listUserAllDeparts(userStore.id).then(departs => {
    userAllDepart.value = departs
    selectItems.value = departs.map(item => ({
      value: item.departCode,
      label: item.departName
    }) as SelectItem)
    for (let depart of departs) {
      if (depart.currentDepart) {
        userCurrentDepart.value = depart
      }
    }
  })
}

/**
 * 确定切换部门
 */
const confirmChangeDepart = () => {
  if (checkedDepartCode.value && checkedDepartCode.value !== userCurrentDepart.value.departCode) {
    loading.value = true
    userApi.updateUserCurrentDepart(userStore.id, checkedDepartCode.value).then(_ => {
      window.location.reload()
    }).finally(() => {
      departDialogVisible.value = false
      loading.value = false
    })
  }
}

/**
 * 取消切换部门
 */
const closeChangeDepart = () => {
  departDialogVisible.value = false
}

/**
 * 确定修改密码
 */
const confirmChangePassword = () => {
  passwordFormRef.value?.validate().then((isPass) => {
    if (isPass) {
      refreshPassword().then(_ => {
        closeChangePassword()
      }).catch(err => {
        console.log(err)
      })
    } else {
      console.error("表单校验未通过")
    }
  })
}

/**
 * 取消修改密码
 */
const closeChangePassword = () => {
  passwordDialogVisible.value = false
  passwordChangeModel.oldPassword = ''
  passwordChangeModel.newPassword = ''
  passwordChangeModel.confirmPassword = ''
}

const refreshPassword = async () => {
  await userApi.refreshPassword({
    userId: userStore.id,
    oldPassword: passwordChangeModel.oldPassword,
    newPassword: passwordChangeModel.newPassword
  })
}

const exit = () => {
  loginApi.logout().then(_ => {
    router.replace('/login')
  })
}

onActivated(() => {
  fetchUserDepart()
})
</script>

<template>
  <div class="home-container">
    <h2 class="section-title">修改密码</h2>
    <div class="home-item password-box">
      <t-btn ghost @click="passwordDialogVisible = true">修改密码</t-btn>

      <!-- 修改密码弹出框 -->
      <t-dialog :visible="passwordDialogVisible" title="修改密码" width="400px"
                @close="closeChangePassword" @confirm="confirmChangePassword">
        <t-form ref="passwordFormRef" :schema="passwordSchema" v-model="passwordChangeModel"/>
      </t-dialog>
    </div>

    <h2 class="section-title">当前部门</h2>
    <div class="home-item depart-box">
      <h3>
        {{
          userCurrentDepart.departName ? userCurrentDepart.departName + ' ' + userCurrentDepart.departCode : '加载中...'
        }}
      </h3>
      <t-btn class="depart-change-btn" ghost @click="departDialogVisible = true">切换部门</t-btn>

      <!-- 切换部门弹出框 -->
      <t-dialog :visible="departDialogVisible" title="切换部门"
                @close="closeChangeDepart" @confirm="confirmChangeDepart">
        <t-table :data="userAllDepart" :columns="tableColumns" :loading="loading"
                 @radioChange="(row: ISysDepartResp) => checkedDepartCode = row.departCode"/>
      </t-dialog>
    </div>


    <h2 class="section-title">退出登录</h2>
    <div class="home-item password-box">
      <t-btn ghost @click="exitDialogVisible = true">退出登录</t-btn>

      <t-dialog :visible="exitDialogVisible" title="是否退出？" width="400px"
                @close="exitDialogVisible = false" @confirm="exit" />
    </div>
  </div>
</template>

<style scoped>
.home-container {
  width: 100%;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  padding-left: 12px;
  border-left: 4px solid #1890ff;
}

.home-item {
  margin-bottom: 25px;
}

.depart-box {
  display: inline-flex;
  align-items: center;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 3px;
  padding: 12px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  font-size: 14px;
  color: #333333;
}

.depart-box span {
  font-weight: 500;
  color: #555;
}

.depart-change-btn {
  margin-left: 24px;
}

.password-box {
  display: inline-flex;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 3px;
  padding: 12px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  font-size: 14px;
  color: #333333;
}

</style>

